﻿// 纯JS省市区三级联动
var addressInit = function (_cmbProvince, _cmbCity, _cmbArea, defaultProvince, defaultCity, defaultArea) {
        var cmbProvince = document.getElementById(_cmbProvince);
        var cmbCity = document.getElementById(_cmbCity);
        var cmbArea = document.getElementById(_cmbArea);

        function cmbSelect(cmb, str) {
            for (var i = 0; i < cmb.options.length; i++) {
                if (cmb.options[i].value == str) {
                    cmb.selectedIndex = i;
                    return;
                }
            }
        }

        function cmbAddOption(cmb, str, key, obj) {
            var option = document.createElement("OPTION");
            cmb.options.add(option);
            option.innerHTML = str;
            option.value = key;
            option.obj = obj;
        }

        function changeCity() {
            cmbArea.options.length = 0;
            if (cmbCity.selectedIndex == -1)return;
            var item = cmbCity.options[cmbCity.selectedIndex].obj;
            if(item.areaList.length==0){
                cmbArea.disabled=true; //禁用地区选择框
            }
            for (var i = 0; i < item.areaList.length; i++) {
                cmbAddOption(cmbArea, item.areaList[i].name,item.areaList[i].id, null);
            }
            cmbSelect(cmbArea, defaultArea);
        }

        function changeProvince() {
            cmbCity.options.length = 0;
            cmbCity.onchange = null;
            cmbCity.disabled=false; //激活城市选择框
            cmbArea.disabled=false; //激活地区选择框
            if (cmbProvince.selectedIndex == -1)return;
            var item = cmbProvince.options[cmbProvince.selectedIndex].obj;
            if(item.cityList.length==0){
                cmbCity.disabled=true; //禁用城市选择框
                cmbArea.disabled=true; //禁用地区选择框
            }
            for (var i = 0; i < item.cityList.length; i++) {
                cmbAddOption(cmbCity, item.cityList[i].name,item.cityList[i].id, item.cityList[i]);
            }
            cmbSelect(cmbCity, defaultCity);
            changeCity();
            cmbCity.onchange = changeCity;
        }

        for (var i = 0; i < provinceList.length; i++) {
            cmbAddOption(cmbProvince, provinceList[i].name,provinceList[i].id, provinceList[i]);
        }
        cmbSelect(cmbProvince, defaultProvince);
        changeProvince();
        cmbProvince.onchange = changeProvince;
}

var provinceList = ['888999'];